﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reactive;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using AppExample.Models;
using DynamicData;
using Newtonsoft.Json;
using ReactiveUI;
using Splat;

namespace AppExample.ViewModels
{
    public class GirlViewModel : ReactiveObject
    {
        private readonly ObservableAsPropertyHelper<List<Girl>> _girls;
        public ReactiveCommand<Unit, List<Girl>> LoadImages { get; private set; }
        public List<Girl> Girls => _girls.Value;

        public GirlViewModel()
        {
            LoadImages = ReactiveCommand.CreateFromTask(LoadImagesAsnyc);

            LoadImages.ThrownExceptions.Subscribe(e =>
            {
                this.Log().Warn("LoadImagesAsnyc: ", e);
            });
        }

        private async Task<List<Girl>> LoadImagesAsnyc()
        {
            var page = _girls.Value.Count / 10 + 1;

            using var http = new HttpClient();
            http.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36");
            var response = await http.GetStringAsync($"http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/{page}");
            var json = JsonConvert.DeserializeObject<Gank>(response);
            if (json.Error == false)
            {
                return json.Results.ToList();
            }

            return Enumerable.Empty<Girl>().ToList();
        }
    }
}